﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BestTrader.Cms.UserCenter.Models;
using Microsoft.Extensions.Logging;
using BestTrader.Cms.Core.Helper;
using System.Security.Claims;
using BestTrader.Cms.IServices;
using BestTrader.Cms.ViewModels;
using FluentValidation.Results;
using BestTrader.Cms.UserCenter.Validation;
using BestTrader.Cms.Services;
using System.Text;
using Microsoft.AspNetCore.Authorization;

namespace BestTrader.Cms.UserCenter.Controllers
{
    /// <summary>
    /// 出入金管理
    /// </summary>
    [Authorize]
    public class InOutCashController : Controller
    {
        public String UserId { get { return User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value; } }
        public String RoleId { get { return User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role)?.Value; } }

        private readonly IUCInOutCashService _service;
        private readonly IManagerService _managerService;
        private readonly IUCAlipayInCashService _aliPayservice;
        private readonly IUCGomePayDFService _ucGomePayService;
        private readonly IManagerRoleService _managerRoleService;

        public InOutCashController(
            IUCInOutCashService service
           ,IManagerService managerService
           ,IUCAlipayInCashService aliPayservice
           ,IUCGomePayDFService ucGomePayService
           ,IManagerRoleService managerRoleService)
        {
            this._service = service;
            this._managerService = managerService;
            this._aliPayservice = aliPayservice;
            _ucGomePayService = ucGomePayService;
            _managerRoleService = managerRoleService;
        }

        #region 1. 直客出入金管理 

        #region 1.1 入金
        /// <summary>
        /// 入金
        /// </summary>
        public IActionResult InCoin() => View();

        /// <summary>
        /// 获取用户入金信息
        /// </summary>
        /// <returns></returns>
        public string GetInCoinUserData() => JsonHelper.ObjectToJSON(_service.LoadInCoinUserData(UserId, RoleId));

        /// <summary>
        /// 用户入金
        /// </summary>
        [HttpPost, ValidateAntiForgeryToken]
        public string AddOrModifyInCoin(InCashModel item)
        {
            var result = new BaseResult();
            InCashValidation validationRules = new InCashValidation();
            ValidationResult results = validationRules.Validate(item);
            if (results.IsValid)
            {
                result = _service.AddOrModifyInCoin(item);
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return JsonHelper.ObjectToJSON(result);
        }

        /// <summary>
        /// 确认入金
        /// </summary>
        [HttpGet]
        public IActionResult ConfirmInCoin([FromQuery]Int32 inCoinId)
        {
            var model = _service.GetInCoinById(inCoinId, UserId);
            var ip4 = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString();
            _aliPayservice.AddYunpayQRCode(model, ip4, UserId);


            return View(model);
        }
        /// <summary>
        /// 获取订单支付详细（内部用）
        /// </summary>
        [HttpGet]
        [AllowAnonymous]
        public string GetYunPayOrderState([FromQuery]int inCashId)
        {
            var ip4 = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString();
            var result = _aliPayservice.GetOrderStateById(inCashId, ip4, UserId);
            return JsonHelper.ObjectToJSON(result);
        }

        /// <summary>
        /// Alipay 第三方回调函数（聂虎团队）
        /// </summary>
        /// <param name="model"></param>
        
        [AllowAnonymous]
        [HttpPost]
        public ContentResult ConfirmAliPayOrder([FromForm]ConfirmAliPayOrderModel model)
        {
            _aliPayservice.ConfirmAliPayOrder(model);
            return Content("ok");
        }

        [HttpPost, ValidateAntiForgeryToken]
        public string ConfirmInCoin(ConfirmInCashModel item)
        {
            var result = new BaseResult();
            ConfirmInCashValidation validationRules = new ConfirmInCashValidation();
            ValidationResult results = validationRules.Validate(item);
            if (results.IsValid)
            {
                result = _service.AuditConfirmInCoin(item, UserId);
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return JsonHelper.ObjectToJSON(result);
        }

        /// <summary>
        /// 线下入金（审核并打款）
        /// </summary>
        /// <param name="inCoinId"></param>
        /// <returns></returns>
        [HttpPost, ValidateAntiForgeryToken]
        public string AuditInCoin([FromQuery]int inCoinId)
        {
            var result = _service.AuditInCoin(inCoinId, UserId);
            return JsonHelper.ObjectToJSON(result);
        }

        [HttpGet]
        public IActionResult AuditCustomInCoin()
        {
            return View();
        }

        [HttpPost, ValidateAntiForgeryToken]
        public string AuditCustomInCoin([FromForm]AuditCustomInCoinModel model)
        {
            var result = new BaseResult();
            AuditCustomInCoinValidation validationRules = new AuditCustomInCoinValidation();
            ValidationResult results = validationRules.Validate(model);
            if (results.IsValid)
            {
                result = _service.AuditCustomInCoin(model, UserId);
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return JsonHelper.ObjectToJSON(result);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public string CancelInCoin([FromQuery]int inCoinId)
        {
            var result = _service.CancelInCoin(inCoinId, UserId);
            return JsonHelper.ObjectToJSON(result);
        }

        #region 1.2 入金记录
        /// <summary>
        /// 入金记录
        /// </summary>
        public IActionResult InCoinRecord()
        {
            return View();
        }

        /// <summary>
        /// 当前用户的入金记录
        /// </summary>
        public string LoadInCoinRecordData([FromQuery]InOutCoinRecordRequestModel model) => JsonHelper.ObjectToJSON(_service.LoadInCoinRecordData(model, UserId, RoleId));

        #endregion

        #endregion

        #region 1.2 出金

        /// <summary>
        /// 出金
        /// </summary>
        public IActionResult OutCoin()
        {
            return View();
        }

        /// <summary>
        /// 获取用户出金信息
        /// </summary>
        /// <returns></returns>
        public string GetOutCoinUserData() => JsonHelper.ObjectToJSON(_service.LoadOutCoinUserData(UserId, RoleId));

        /// <summary>
        /// 出金记录
        /// </summary>
        public IActionResult OutCoinRecord()
        {
            ViewData["AgentManagers"] = _managerService.GetSelfAndChildManagerByManagerIdAndRoleId(UserId, RoleId);
            return View();
        }

        /// <summary>
        /// 当前用户的入金记录
        /// </summary>
        public string LoadOutCoinRecordData([FromQuery]InOutCoinRecordRequestModel model) => JsonHelper.ObjectToJSON(_service.LoadOutCoinRecordData(model, UserId, RoleId));

        /// <summary>
        /// 用户出金
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [HttpPost, ValidateAntiForgeryToken]
        public string AddOrModifyOutCoin(OutCashModel item)
        {
            var result = new BaseResult();
            OutCashValidation validationRules = new OutCashValidation();
            ValidationResult results = validationRules.Validate(item);
            if (results.IsValid)
            {
                result = _service.AddOrModifyOutCoin(item);
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return JsonHelper.ObjectToJSON(result);
        }

        /// <summary>
        /// 审核用户出金，需要扣除手续费 6点前3块，6点后5块
        /// </summary>
        /// <param name="inCoinId"></param>
        /// <returns></returns>
        [HttpPost, ValidateAntiForgeryToken]
        public string AuditOutCoin([FromQuery]int inCoinId)
        {
            var result = _service.AuditOutCoin(inCoinId, UserId);
            return JsonHelper.ObjectToJSON(result);
        }
        /// <summary>
        /// 审核美付宝
        /// </summary>
        /// <param name="inCoinId"></param>
        /// <returns></returns>
        [HttpPost, ValidateAntiForgeryToken]
        public string AuditGomePayOutCoin([FromQuery]int inCoinId, string gomePwd)
        {
            var result = new BaseResult() { Success = false };
            if (gomePwd != null && inCoinId > 0)
            {

                byte[] bytes = Convert.FromBase64String(gomePwd);
                var gomePayPwd = Encoding.Default.GetString(bytes);

                result = _service.AuditGomePayOutCoin(inCoinId, UserId, gomePayPwd);
            }
            else {
                result.ResultCode = ResultCodeAddMsgKeys.CommonParamsErrorCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonParamsErrorMsg;
            }


            return JsonHelper.ObjectToJSON(result);
        }

        /// <summary>
        /// 获取用户资金账户余额
        /// 1.获取风软接口余额
        /// </summary>
        /// <param name="inCoinId"></param>
        /// <returns></returns>
        [HttpPost, ValidateAntiForgeryToken]
        public string GetAccountBalance([FromQuery] string username)
        {
            var result = new TableDataResult<RmmfAccountBalanceOutput>(){ Success = false };
            if (username !=null)
            {
                result = _service.GetRmmfAccountBalanceByUserName(username);
                result.Success = true;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonParamsErrorCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonParamsErrorMsg;
            }
            return JsonHelper.ObjectToJSON(result);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public string CancelOutCoin([FromQuery]int inCoinId)
        {
            var ip4 = HttpContext.Connection.LocalIpAddress.MapToIPv4();
            var result = _service.CancelOutCoin(inCoinId, UserId);
            return JsonHelper.ObjectToJSON(result);
        }
        #endregion

        #endregion

        #region 2. 营业部出入金管理

        /// <summary>
        /// 线上入金管理 
        /// </summary>
        public IActionResult OfflineInCash()
        {
            ViewData["AgentManagers"] = _managerService.GetSelfAndChildManagerByManagerIdAndRoleId(UserId, RoleId);
            return View();
        }

        /// <summary>
        /// 出金记录列表
        /// </summary>
        public string LoadOfflineInCashRecordData([FromQuery]InOutCoinRecordRequestModel model) => JsonHelper.ObjectToJSON(_service.LoadOfflineInCashRecordData(model, UserId, RoleId));


        /// <summary>
        /// 线下入金管理 
        /// </summary>
        public IActionResult OnlineInCash()
        {
            ViewData["AgentManagers"] = _managerService.GetSelfAndChildManagerByManagerIdAndRoleId(UserId, RoleId);
            return View();
        }

        /// <summary>
        /// 出金记录列表
        /// </summary>
        public string LoadOnlineInCashRecordData([FromQuery]InOutCoinRecordRequestModel model) => JsonHelper.ObjectToJSON(_service.LoadOnlineInCashRecordData(model, UserId, RoleId));


        /// <summary>
        /// 出金管理
        /// </summary>
        public IActionResult OutCash()
        {
            ViewData["IsFinanceAdmin"] = _managerRoleService.CheckIsFinanceAdmin(UserId);
            ViewData["AgentManagers"] = _managerService.GetSelfAndChildManagerByManagerIdAndRoleId(UserId, RoleId);
            return View();
        }

        /// <summary>
        /// 出金记录列表
        /// </summary>
        public string LoadOutCashRecordData([FromQuery]InOutCoinRecordRequestModel model) => JsonHelper.ObjectToJSON(_service.LoadOutCashRecordData(model, UserId, RoleId));

        /// <summary>
        /// 美付宝代付记录
        /// </summary>
        /// <returns></returns>
        public IActionResult GomePayOutCash()
        {
            ViewData["AgentManagers"] = _managerService.GetSelfAndChildManagerByManagerIdAndRoleId(UserId, RoleId);
            return View();
        }
        /// <summary>
        /// 美付宝出金记录列表
        /// </summary>
        public string LoadGomePayOutCashRecordData([FromQuery]InOutCoinRecordRequestModel model) => JsonHelper.ObjectToJSON(_ucGomePayService.LoadOutCashRecordData(model, UserId, RoleId));

        /// <summary>
        /// 获取支付结果
        /// </summary>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        [HttpPost, ValidateAntiForgeryToken]
        public string GetGomePayResultByOrderNo([FromQuery] string orderNo)
        {
            var result = new TableDataResult<GomePayDFBillOutput>() { Success = false };
            if (orderNo != null)
            {
                result = _service.GetGomePayOrderState(orderNo);
                result.Success = true;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonParamsErrorCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonParamsErrorMsg;
            }
            return JsonHelper.ObjectToJSON(result);
        }



        #endregion


    }
}
